package com.zzyang.mybatis.jdbc.core;

import com.zzyang.mybatis.jdbc.enums.DataSourceType;
import org.apache.ibatis.transaction.Transaction;
import org.mybatis.spring.transaction.SpringManagedTransaction;
import org.springframework.core.NamedThreadLocal;

/**
 * 存储 每个线程下一次应用的数据源
 *
 * @author zhuoziyang
 * @date 2021/4/8 22:01
 */
public class DataSourceSynchronizationManager {

    private DataSourceSynchronizationManager() {
    }

    private static final ThreadLocal<DataSourceType> DATA_SOURCE_TYPE_HOLDER = new NamedThreadLocal<>("DATA_SOURCE_TYPE_HOLDER");

    /**
     * 是否使用主数据源
     */
    private static final ThreadLocal<Boolean> MASTER_ONLY = new NamedThreadLocal<>("MASTER_ONLY");

    /**
     * 从数据源的名称
     */
    private static final ThreadLocal<String> SLAVE_DATA_SOURCE_ID = new NamedThreadLocal<>("SLAVE_DATA_SOURCE_ID");

    public static void setDataSourceType(DataSourceType dataSourceType) {
        DATA_SOURCE_TYPE_HOLDER.set(dataSourceType);
    }

    public static DataSourceType getDataSourceType() {
        return DATA_SOURCE_TYPE_HOLDER.get();
    }

    public static void removeDataSourceType() {
        DATA_SOURCE_TYPE_HOLDER.remove();
    }

    public static void forceUseMaster() {
        setDataSourceType(DataSourceType.MASTER);
        MASTER_ONLY.set(true);
    }

    public static boolean isForceUseMaster() {
        Boolean aBoolean = MASTER_ONLY.get();
        MASTER_ONLY.remove();
        return Boolean.TRUE.equals(aBoolean);
    }

    public static void setSlaveDataSourceId(String slaveDataSourceId) {
        SLAVE_DATA_SOURCE_ID.set(slaveDataSourceId);
    }

    public static String getSlaveDataSourceId() {
        return SLAVE_DATA_SOURCE_ID.get();
    }

    public static void removeSlaveDataSourceId() {
        SLAVE_DATA_SOURCE_ID.remove();
    }

}
